package com.cocolover2.andbase.widget;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cocolover2.andbase.R;

import java.lang.reflect.Field;
import java.util.Arrays;

/**
 * icon+编辑框+清空按钮+密码显示隐藏按钮
 * Created by cocolove2 on 17/6/16.
 */
@SuppressWarnings("unused")
public class SuperEditText extends LinearLayout implements View.OnFocusChangeListener, TextWatcher {
    private static final float ICON_SIZE = 0;
    private ImageView iconIv;
    private EditText inputEt;
    private ImageView clearIv;
    private ImageView extendIv;

    private Drawable iconDrawable;
    private Drawable clearDrawable;
    private Drawable extendDrawable;

    private int iconWidth;
    private int iconHeight;
    private int clearWidth;
    private int clearHeight;
    private int extendWidth;
    private int extendHeight;

    private int clearToeyePadding;
    private int editPadding;

    private String hint;
    private int hintColor;
    private float textSize;
    private int textColor;
    private int inputType;
    private int textCursorDrawableId;

    private OnFocusChangeListener mOnFocusChangeListener;
    private OnClickListener mEditClickListener;
    private OnClickListener mExendClickListener;

    public SuperEditText(Context context) {
        super(context);
        init(context, null);
    }

    public SuperEditText(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public SuperEditText(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    @TargetApi(21)
    public SuperEditText(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        setGravity(Gravity.CENTER_VERTICAL);
        setOrientation(HORIZONTAL);

        int[] styleable = R.styleable.SuperEditText;
        int[] attrArr = Arrays.copyOf(styleable, styleable.length + 1);
        attrArr[attrArr.length - 1] = android.R.attr.inputType;

        final float density = getResources().getDisplayMetrics().density;
        TypedArray array = context.obtainStyledAttributes(attrs, attrArr);
        iconDrawable = array.getDrawable(R.styleable.SuperEditText_iconDrawable);
        clearDrawable = array.getDrawable(R.styleable.SuperEditText_clearDrawable);
        iconWidth = (int) array.getDimension(R.styleable.SuperEditText_iconWidth, ICON_SIZE);
        iconHeight = (int) array.getDimension(R.styleable.SuperEditText_iconHeight, ICON_SIZE);
        clearWidth = (int) array.getDimension(R.styleable.SuperEditText_clearWidth, ICON_SIZE);
        clearHeight = (int) array.getDimension(R.styleable.SuperEditText_clearHeight, ICON_SIZE);
        extendWidth = (int) array.getDimension(R.styleable.SuperEditText_extendWidth, ICON_SIZE);
        extendHeight = (int) array.getDimension(R.styleable.SuperEditText_extendHeight, ICON_SIZE);
        extendDrawable = array.getDrawable(R.styleable.SuperEditText_extendDrawable);
        editPadding = (int) array.getDimension(R.styleable.SuperEditText_editPadding, ICON_SIZE);
        clearToeyePadding = (int) array.getDimension(R.styleable.SuperEditText_clearToeyePadding, ICON_SIZE);
        hint = array.getString(R.styleable.SuperEditText_hint);
        hintColor = array.getColor(R.styleable.SuperEditText_hintColor, Color.LTGRAY);
        textColor = array.getColor(R.styleable.SuperEditText_textColor, Color.BLACK);
        textSize = array.getDimensionPixelSize(R.styleable.SuperEditText_textSize, 15);
        textCursorDrawableId = array.getResourceId(R.styleable.SuperEditText_textCursorDrawable, 0);
        inputType = array.getInt(attrArr.length - 1, TypedValue.TYPE_NULL);
        array.recycle();
        initIconView(context);
        initEditText(context);
        initClearView(context);
        initEyeView(context);
        addView(iconIv);
        addView(inputEt);
        addView(clearIv);
        addView(extendIv);
    }

    private void initIconView(Context context) {
        iconIv = new ImageView(context);
        iconIv.setLayoutParams(new LinearLayout.LayoutParams(iconWidth > 0 ? iconWidth : LayoutParams.WRAP_CONTENT,
                iconHeight > 0 ? iconHeight : LayoutParams.WRAP_CONTENT));
        iconIv.setImageDrawable(iconDrawable);
    }

    private void initEditText(Context context) {
        inputEt = new EditText(context);
        inputEt.setLayoutParams(new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 1));
        inputEt.setBackground(null);
        inputEt.setHintTextColor(hintColor);
        inputEt.setInputType(inputType);
        inputEt.setSingleLine();
        if (textCursorDrawableId != 0)
            setCursorDrawable(textCursorDrawableId);
        inputEt.setPadding(editPadding, 0, editPadding, 0);
        inputEt.setGravity(Gravity.CENTER_VERTICAL);
        inputEt.addTextChangedListener(this);
        inputEt.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                setClearIconVisible(((EditText) v).getText().length() > 0);
                if (mEditClickListener != null)
                    mEditClickListener.onClick(v);
            }
        });
        inputEt.setOnFocusChangeListener(this);
        inputEt.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
        inputEt.setTextColor(textColor);
        inputEt.setHint(hint);
    }

    private void initClearView(Context context) {
        clearIv = new ImageView(context);
        clearIv.setVisibility(INVISIBLE);
        clearIv.setLayoutParams(new LinearLayout.LayoutParams(clearWidth > 0 ? clearWidth : LayoutParams.WRAP_CONTENT,
                clearHeight > 0 ? clearHeight : LayoutParams.WRAP_CONTENT));
        clearIv.setImageDrawable(clearDrawable);
        clearIv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                inputEt.setText("");
            }
        });
    }

    private void initEyeView(Context context) {
        extendIv = new ImageView(context);
        MarginLayoutParams eyeParams = new LinearLayout.LayoutParams(extendWidth > 0 ? extendWidth : LayoutParams.WRAP_CONTENT,
                extendHeight > 0 ? extendHeight : LayoutParams.WRAP_CONTENT);
        eyeParams.leftMargin = clearToeyePadding;
        extendIv.setLayoutParams(eyeParams);
        extendIv.setImageDrawable(extendDrawable);
        extendIv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mExendClickListener != null) {
                    mExendClickListener.onClick(v);
                }
            }
        });
    }

    public void setExendClickListener(OnClickListener listener) {
        mExendClickListener = listener;
    }


    /**
     * 设置输入类型
     *
     * @param type {@link EditText#setInputType(int)}
     */
    public void setInputType(int type) {
        inputEt.setInputType(type);
    }

    public int getInputType() {
        return inputEt.getInputType();
    }

    public void setTextSize(int sp_size) {
        inputEt.setTextSize(sp_size);
    }

    public float getTextSize() {
        return inputEt.getTextSize();
    }

    public void setIconDrawable(Drawable iconDrawable) {
        iconIv.setImageDrawable(iconDrawable);
    }

    public void setIconResource(int resId) {
        iconIv.setImageResource(resId);
    }

    public Drawable getIconDrawable() {
        return iconIv.getDrawable();
    }

    public void setClearDrawable(Drawable clearDrawable) {
        clearIv.setImageDrawable(clearDrawable);
    }

    public void setClearResource(int resId) {
        clearIv.setImageResource(resId);
    }

    public Drawable getClearDrawable() {
        return clearIv.getDrawable();
    }

    public void setExtendDrawable(Drawable drawable) {
        extendIv.setImageDrawable(drawable);
    }

    public void setExtendResource(int resId) {
        extendIv.setImageResource(resId);
    }

    public Drawable getExtendDrawable() {
        return extendIv.getDrawable();
    }

    public void setIconSize(int iconWidth, int iconHeight) {
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) iconIv.getLayoutParams();
        lp.width = iconWidth;
        lp.height = iconHeight;
        iconIv.setLayoutParams(lp);
    }

    public void setClearSize(int clearWidth, int clearHeight) {
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) clearIv.getLayoutParams();
        lp.width = clearWidth;
        lp.height = clearHeight;
        clearIv.setLayoutParams(lp);
    }

    public void setEyeSize(int eyeWidth, int eyeHeight) {
        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) extendIv.getLayoutParams();
        lp.width = eyeWidth;
        lp.height = eyeHeight;
        extendIv.setLayoutParams(lp);
    }

    public void setClearToeyePadding(int clearToeyePadding) {
        MarginLayoutParams lp = (MarginLayoutParams) extendIv.getLayoutParams();
        lp.leftMargin = clearToeyePadding;
        extendIv.setLayoutParams(lp);
    }

    public void setEditPadding(int editPadding) {
        inputEt.setPadding(editPadding, 0, editPadding, 0);
    }

    public void setHint(String hint) {
        inputEt.setHint(hint);
    }

    public CharSequence getHint() {
        return inputEt.getHint();
    }

    public void setText(String text) {
        inputEt.setText(text);
    }

    public Editable getText() {
        return inputEt.getText();
    }

    public void setTextColor(int textColor) {
        inputEt.setTextColor(textColor);
    }

    public int getTextColor() {
        return textColor;
    }

    public void setHintColor(int color) {
        inputEt.setHintTextColor(color);
    }

    public int getHintColor() {
        return hintColor;
    }

    /**
     * 通过反射设置自定义光标
     *
     * @param drawableId 光标资源Id
     */
    @SuppressWarnings("all")
    private void setCursorDrawable(int drawableId) {
        try {
            Field f = TextView.class.getDeclaredField("mCursorDrawableRes");
            f.setAccessible(true);
            f.set(inputEt, drawableId);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public void setSelection(int index) {
        inputEt.setSelection(index);
    }

    public void addTextWatcher(TextWatcher textWatcher) {
        inputEt.addTextChangedListener(textWatcher);
    }


    public void setEditFocusChangeListener(OnFocusChangeListener onFocusChangeListener) {
        mOnFocusChangeListener = onFocusChangeListener;
    }

    public void setEditClickListener(OnClickListener listener) {
        mEditClickListener = listener;
    }

    /**
     * 设置清除图标的显示与隐藏，调用setCompoundDrawables为EditText绘制上去
     */
    public void setClearIconVisible(boolean visible) {
        clearIv.setVisibility(visible ? VISIBLE : INVISIBLE);
    }

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (hasFocus) {
            setClearIconVisible(((EditText) v).getText().length() > 0);
        } else {
            setClearIconVisible(false);
        }
        if (mOnFocusChangeListener != null)
            mOnFocusChangeListener.onFocusChange(v, hasFocus);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (inputEt.isFocused())
            setClearIconVisible(s.length() > 0);
    }

    @Override
    public void afterTextChanged(Editable s) {
    }

}
